import socket

receivebuf = bytes()
def netexchange(udpsocket, targetaddr, sendlist):
	global receivebuf
	receivelist = []
	
	for i in range(100):
		try:
			data,addr = udpsocket.recvfrom(1024)
			receivebuf += data
		except socket.timeout:
			break
			
	splitbuf = receivebuf.split(b"&&")
	receivebuf = splitbuf[len(splitbuf) - 1]
	
	for bytedata in splitbuf[:-1]:
		data = str(bytedata, "big5")
		receivelist.append(data)
		#print("\nReceived message %s....." % (data))
		pass
		
	if targetaddr:
		if sendlist:
			#print(sendlist)
			pass
		
		numofpair = 16
		sendlist8pair = []
		for i in range(len(sendlist) // numofpair + 1):
			senddata8pair = b""
			for data in sendlist[i*numofpair:(i+1)*numofpair]:
				senddata = bytes(data + "&&", "big5")
				senddata8pair += senddata
			
			sendlist8pair.append(senddata8pair)
		
		i+=1
		#if len(sendlist) > 0:
		#	print("i*numofpair: " + str(i*numofpair))
		#	print("len(sendlist): " + str(len(sendlist) ))
		#	print(sendlist8pair)
		
		if i*numofpair < len(sendlist):
			senddata8pair = b""
			for data in sendlist[i*numofpair:len(sendlist)]:
				senddata = bytes(data + "&&", "big5")
				senddata8pair += senddata
			sendlist8pair.append(senddata8pair)
			
		for data in sendlist8pair:
			if(udpsocket.sendto(data, 0, targetaddr)):
				#print("Sending message %s....." % (data))
				pass
			
	return receivelist
	
def createudp_server(port, waitcallback=None):
	host = ""
	port = port
	addr = (host,port)

	# Create socket and bind to address
	udpsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	udpsocket.bind(addr)
	udpsocket.setblocking(1)
	udpsocket.settimeout(0.01)
	while(1):
		try:
			if waitcallback != None:
				waitcallback()
				
			data,targetaddr = udpsocket.recvfrom(1024)
			if data == b"link":
				print(targetaddr)
				udpsocket.sendto(b"accept", 0, targetaddr)
				break
			print(waitcallback)
			
		except socket.timeout:
			pass
			
	return (udpsocket, targetaddr)
	
def createudp_client(ip, port, waitcallback=None):
	targetaddr = (ip, port)
	udpsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	udpsocket.setblocking(1)
	udpsocket.settimeout(0.01)
	udpsocket.sendto(b"link", 0, targetaddr)
	while(1):
		try:
			if waitcallback != None:
				waitcallback()
			data,addr = udpsocket.recvfrom(1024)
			if data == b"accept":
				print(addr)
				break
			
		except socket.timeout:
			pass
			
	return (udpsocket, targetaddr)